package com.acceptable.qucun.user.interceptor;

import com.acceptable.qucun.generic.util.CodeUtil;
import com.acceptable.qucun.generic.util.StringFormatUtil;
import com.acceptable.qucun.generic.util.verify.FormatVerifyUtil;
import com.acceptable.qucun.user.entity.User;
import com.acceptable.qucun.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class AccountBoundInterceptor implements HandlerInterceptor {
    @Autowired private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        Map<String, String> dataMap = (Map<String, String>) request.getAttribute("data_map");
        User user = null;
        if (!FormatVerifyUtil.mapIsEmpty(dataMap)){
            String email = dataMap.get("email");
            user = userMapper.selectByEmail(email);
        } else{
            dataMap = new HashMap<>();
        }

        // 用user_id查找
        if (user == null){
            String userIdStr;
            boolean isGet = request.getMethod().toLowerCase().equals("get");
            if (isGet){
                userIdStr = CodeUtil.object2String(request.getParameter("user_id"));
                if (StringFormatUtil.isEmpty(userIdStr))
                    userIdStr = CodeUtil.object2String(request.getParameter("src_user_id"));
                userIdStr = userIdStr.replace("\"", "");
            }else{
                userIdStr = dataMap.get("user_id");
                if (StringFormatUtil.isEmpty(userIdStr))
                    userIdStr = dataMap.get("src_user_id");
            }
//            System.out.println(userIdStr);
            if (!StringFormatUtil.isEmpty(userIdStr)){
                Integer userId = Integer.parseInt(userIdStr);
                user = userMapper.selectByUserId(userId);
            } else if (isGet){
                // 为空 且是get方式进行请求 直接拦截住
                return false;
            }
        }
//        System.out.println(user);
        if (user != null && user.getDeleteTime() != null){
            user.setDeleteTimeStr(user.getDeleteTime().toString());
            user.setDeleteTime(null);
        }

        dataMap.put("user", CodeUtil.object2String(user));
        request.setAttribute("data_map", dataMap);
        return true;
    }
}
